extends Object
var path:String
var pck_version:String
var engine_version:String
var files:Array= []
var filePack:File
var finishCount = 0
var saveDir:String
enum PCK_STATE{
	NONE = 0,
	Decompress_Start = 1,
	Decompress_FINSH = 2
}
var state = PCK_STATE.NONE
class PCKFile:
	var md5:String
	var path:String
	var offset:int
	var size:int
	
func _init(filePath:String):
	self.path=filePath
	
func decompression(saveDir):
	self.saveDir = saveDir
	self.state= PCK_STATE.Decompress_Start
	
func saveFile(pckFile:PCKFile,saveDir:String):
	var savePath = saveDir + "/" + pckFile.path
	var dir = Directory.new()
	dir.make_dir_recursive(savePath.get_base_dir())
	var old_pos = self.filePack.get_position()
	self.filePack.seek(pckFile.offset)
	var file = File.new()
	file.open(savePath,File.WRITE)
	file.store_buffer(self.filePack.get_buffer(pckFile.size))
	file.close()
	self.filePack.seek(old_pos)
	
func getProgress():
	return "%d/%d" % [finishCount,len(files)]
	
func _process(dt):
	if self.state==PCK_STATE.Decompress_Start:
		if finishCount<len(files):
			saveFile(files[finishCount],self.saveDir)
			finishCount +=1
		else:
			self.state=PCK_STATE.Decompress_FINSH
	return self.state
	
func parse():
	var file:File = File.new()
	var  err = file.open(self.path, File.READ)
	if err != OK:
		print("Error: %s open failed,error code %d" % [self.path,err])
		file.close()
		return false
	var magic:PoolByteArray = file.get_buffer(4)
	if not magic.get_string_from_utf8()=="GDPC":
		file.close()
		print("Error: %s is not PCK file" % [self.path])
		return false
	var version = file.get_32()
	var ver_major = file.get_32()
	var ver_minor = file.get_32()
	var ver_rev = file.get_32()
	print("version:",version," ver_major:",ver_major," ver_minor:",ver_minor," ver_rev:",ver_rev)
	self.pck_version=str(version)
	if ver_major<3 or (ver_major==3 and ver_minor<2):
		self.engine_version="%d.%d.x" % [ver_major,ver_minor]
	else:
		self.engine_version="%d.%d.%d" % [ver_major,ver_minor,ver_rev]
	print(self.pck_version," ",self.engine_version)
	file.seek(file.get_position()+64)
	var file_count = file.get_32()
	self.filePack = file
	for __ in range(0,file_count):
		var pck_file = PCKFile.new()
		pck_file.path = file.get_buffer(file.get_32()).get_string_from_utf8().replace("res://","")
		pck_file.offset = file.get_64()
		pck_file.size = file.get_64()
		pck_file.md5 = file.get_buffer(16).hex_encode()
		files.append(pck_file)
	return true

